package com.hrd.admin.util;

import com.smecloud.apigw.exception.ApiException;
import com.smecloud.apigw.http.HttpClient;
import com.smecloud.apigw.model.ApiCallBack;
import com.smecloud.apigw.model.ApiRequest;
import com.smecloud.apigw.model.ApiResult;
import com.smecloud.apigw.model.ApigwConfig;
import com.smecloud.apigw.util.CommontUtil;
import com.smecloud.apigw.util.SHAUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.*;

public class TestDemo  extends HttpClient{
    private ApigwConfig config;
    private static final String AUTH_VERSION = "2.0";
    private static final TestDemo instance = new TestDemo();
    private static final String[] DEFAULT_SIGNHEADERS = new String[]{"X-Api-Nonce", "X-Api-TimeStamp"};
    private final Random rand = new SecureRandom();

    public TestDemo() {
    }

    public void init(ApigwConfig config) {
        super.init(config);
        this.config = config;
    }

    public static TestDemo getInstance() {
        return instance;
    }

    public ApiResult send(ApiRequest apiRequest) {
        this.setSignature(apiRequest);
        return super.syncRequest(apiRequest);
    }

    public void downloadFile(ApiRequest apiRequest, String filepath) {
        this.setSignature(apiRequest);
        super.downloadFile(apiRequest, filepath);
    }

    public void asyncSend(ApiRequest apiRequest, ApiCallBack apiCallback) {
        this.setSignature(apiRequest);
        super.asyncRequest(apiRequest, apiCallback);
    }

    private void setSignature(ApiRequest apiRequest) {
        String[] signHeaders;
        if (apiRequest.getSignHeaders().size() > 0) {
            List<String> s = apiRequest.getSignHeaders();
            s.addAll(Arrays.asList(DEFAULT_SIGNHEADERS));
            Collections.sort(s);
            signHeaders = (String[])s.toArray(new String[s.size()]);
        } else {
            signHeaders = DEFAULT_SIGNHEADERS;
        }

        apiRequest.addHeader("X-Api-ClientID", this.config.getClientID());
        apiRequest.addHeader("X-Api-Auth-Version", "2.0");
        apiRequest.addHeader("X-Api-TimeStamp", this.getTimestamp());
        apiRequest.addHeader("X-Api-Nonce", this.getNonce(10));
        apiRequest.addHeader("X-Api-SignHeaders", String.join(",", signHeaders));
        apiRequest.addHeader("X-Api-Signature", this.getSignature(apiRequest.getMethod().getValue(), this.getPathEncode(apiRequest.getPath()), this.getQueryEncode(apiRequest.getQuerys()), signHeaders, apiRequest.getHeaders()));
    }

    private String getPathEncode(String path) {
        try {
            return URLEncoder.encode(path, StandardCharsets.UTF_8.toString());
        } catch (Exception var3) {
            throw new ApiException(var3);
        }
    }

    private String getTimestamp() {
        return Long.toString(System.currentTimeMillis());
    }

    public String getNonce(int len) {
        StringBuilder rs = new StringBuilder();

        for(int i = 0; i < len; ++i) {
            rs.append(this.rand.nextInt(10));
        }

        return rs.toString();
    }

    private String getQueryEncode(Map<String, String> querys) {
        try {
            if (CommontUtil.isEmpty(querys)) {
                return "";
            } else {
                List<String> list = new ArrayList(querys.size());
                Iterator var3 = querys.entrySet().iterator();

                while(var3.hasNext()) {
                    Map.Entry<String, String> entry = (Map.Entry)var3.next();
                    String key = URLEncoder.encode((String)entry.getKey(), StandardCharsets.UTF_8.toString());
                    String value = URLEncoder.encode((String)entry.getValue(), StandardCharsets.UTF_8.toString());
                    list.add(key + "=" + value);
                }

                Collections.sort(list);
                String rawQueryString = String.join("&", list);
                String[] queryStrings = rawQueryString.split("&");
                list.clear();
                String[] var15 = queryStrings;
                int var16 = queryStrings.length;

                for(int var7 = 0; var7 < var16; ++var7) {
                    String param = var15[var7];
                    int index = param.indexOf("=");
                    if (index >= 1) {
                        String key = URLEncoder.encode(param.substring(0, index), StandardCharsets.UTF_8.toString());
                        String value = URLEncoder.encode(param.substring(index + 1), StandardCharsets.UTF_8.toString());
                        list.add(key + "=" + value);
                    }
                }

                return String.join("&", list);
            }
        } catch (Exception var12) {
            throw new ApiException(var12);
        }
    }

    private String getSignature(String method, String path, String query, String[] signatureHeaders, Map<String, String> headers) {
        StringBuilder b = new StringBuilder();
        b.append(method);
        b.append("\n");
        b.append(path);
        b.append("\n");
        b.append(query);
        b.append("\n");
        String[] var7 = signatureHeaders;
        int var8 = signatureHeaders.length;

        for(int var9 = 0; var9 < var8; ++var9) {
            String x = var7[var9];
            b.append(x.toLowerCase());
            b.append(":");
            b.append((String)headers.get(x));
            b.append("\n");
        }
        String str = StringUtils.substringBeforeLast(b.toString(), "\n");

        String s = SHAUtil.SHA256HMAC(str, this.config.getClientSecret());
        return s != null ? Base64.encodeBase64String(s.getBytes()) : "";
    }
}
